package com.uzai.console.service.remoteapi.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.dto.base.BizLog;
import com.uzai.common.dto.pyq.FeedMedia;
import com.uzai.common.dto.wxgroup.WxGroupAddBlacklistDto;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.msg.NoticeMsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Mobiletype;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.Const;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.dto.feign.uzaimanage.SysRunlogWarningDto;
import com.uzai.console.dto.pyq.pyqfollowedContent.PyqFollowedContentQuery;
import com.uzai.console.dto.pyq.pyqjobdetail.PyqJobDetailIdDto;
import com.uzai.console.dto.pyq.pyqjobdetail.PyqJobDetailQuery;
import com.uzai.console.dto.remoteapi.*;
import com.uzai.console.dto.report.FansValueReportQuery;
import com.uzai.console.dto.rocketmq.wechatuser.SetUserRemarkDto;
import com.uzai.console.dto.tb.tbtoken.TbTokenQuery;
import com.uzai.console.dto.user.wechatblacklist.WechatBlacklistPrvIdDto;
import com.uzai.console.dto.user.wechatuser.UpdateDefaultClientPersonal;
import com.uzai.console.dto.uzaichat.kefuclient.KefuClientQuery;
import com.uzai.console.dto.wechatprivate.friendrequest.FriendRequestIdListDto;
import com.uzai.console.dto.wechatprivate.wxq.manageplan.WxqGroupManagePlanQuery;
import com.uzai.console.dto.wechatprivate.wxq.wxgroupmenber.WxGroupMemberBlacklistDto;
import com.uzai.console.dto.wechatwork.wxq.manageplan.WxqWorkGroupManagePlanQuery;
import com.uzai.console.entity.*;
import com.uzai.console.entity.es.EsWorkWxGroupInfo;
import com.uzai.console.entity.es.EsWxContacts;
import com.uzai.console.entity.es.PyqJobDetail;
import com.uzai.console.enums.MerAccDetailSourceTypeEnum;
import com.uzai.console.enums.ZombieFanTaskStatusEnum;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.feign.UzaiCashierAdminFeignService;
import com.uzai.console.service.feign.UzaiManageFeignService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.pyq.PyqJobDetailService;
import com.uzai.console.service.ratelimit.RatelimitService;
import com.uzai.console.service.remoteapi.RemoteApiService;
import com.uzai.console.service.report.FansValueReportService;
import com.uzai.console.service.reportpanel.BaseDataPanelService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.user.WechatBlacklistPrvService;
import com.uzai.console.service.wechatprivate.DeviceWechatInfoService;
import com.uzai.console.service.wechatprivate.FriendRequestService;
import com.uzai.console.service.wechatprivate.WxGroupMemberService;
import com.uzai.console.service.xxljob.XxlJobSyncService;
import com.uzai.console.utils.DataPanelHolder;
import com.uzai.console.vo.alarm.alarmrule.AlarmRuleContentVo;
import com.uzai.console.vo.device.DeviceInfoVo;
import com.uzai.console.vo.pyq.pyqfollowedcontent.PyqFollowedItemVo;
import com.uzai.console.vo.pyq.pyqjobdetail.PyqJobDetailVo;
import com.uzai.console.vo.remoteapi.cashier.CashierAuthpayContentVo;
import com.uzai.console.vo.remoteapi.reportbanel.ReportBanelFansValueReportVo;
import com.uzai.console.vo.report.FansValueReportVo;
import com.uzai.console.vo.wechatprivate.friendrequest.FriendRequestInfoVo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/**
 * @Auther: liuqi
 * @Date: 2019/11/27 11:23
 * @Description:
 */
@Service
public class RemoteApiServiceImpl implements RemoteApiService {

    private static Logger logger = LoggerFactory.getLogger(RemoteApiServiceImpl.class);

    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private UzaiCashierAdminFeignService uzaiCashierAdminFeignService;
    @Autowired
    private FansValueReportService fansValueReportService;
    @Autowired
    private ReportPanelMapper reportPanelMapper;
    @Autowired
    private DataPanelMapper dataPanelMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private WxqGroupManagePlanMapper wxqGroupManagePlanMapper;
    @Autowired
    private WxqWorkGroupManagePlanMapper wxqWorkGroupManagePlanMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private PyqAutoSendMapper pyqAutoSendMapper;
    @Autowired
    private FriendRequestService friendRequestService;
    @Autowired
    private DataPanelHolder dataPanelHolder;
    @Autowired
    private PyqJobDetailService pyqJobDetailService;
    @Autowired
    private ZombieFanTaskMapper zombieFanTaskMapper;
    @Autowired
    private WxGroupMemberService wxGroupMemberMemberService;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private KefuClientMapper kefuClientMapper;
    @Autowired
    private DeviceWechatInfoService deviceWechatInfoService;
    @Autowired
    private AlarmRuleMapper alarmRuleMapper;
    @Autowired
    private MerAccDetailMapper merAccDetailMapper;
    @Autowired
    private MerMobileRechargeMapper merMobileRechargeMapper;
    @Autowired
    private UzaiManageFeignService uzaiManageFeignService;
    @Autowired
    private WechatBlacklistPrvService wechatBlacklistPrvService;
    @Autowired
    private PyqFollowedContentMapper pyqFollowedContentMapper;
    @Autowired
    private PyqFollowedCommentMapper pyqFollowedCommentMapper;
    @Autowired
    private XxlJobSyncService xxlJobSyncService;
    @Autowired
    private ZombieFanPassiveMapper zombieFanPassiveMapper;

    /**
     * 发送淘宝订单下载限流报警消息
     *
     * @param sendAlarmMsgTbOrderDownloadLimitDto
     * @return null
     * @author liuqi
     * @date 2022/11/23 11:38
     */
    @Async("taskExecutor")
    @Override
    public void sendAlarmMsgTbOrderDownloadLimit(SendAlarmMsgTbOrderDownloadLimitDto sendAlarmMsgTbOrderDownloadLimitDto) {

        if(sendAlarmMsgTbOrderDownloadLimitDto.getTbTokenUserId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入淘宝联盟会员id");
        }

        TbToken tbToken = tbTokenMapper.selectByUserIdAndTurnLink(sendAlarmMsgTbOrderDownloadLimitDto.getTbTokenUserId(), 0);
        if(tbToken == null){
            tbToken = tbTokenMapper.selectByUserIdAndTurnLink(sendAlarmMsgTbOrderDownloadLimitDto.getTbTokenUserId(), 1);
        }
        //不等于空，表示是3.0的运营商的淘宝联盟
        if(tbToken != null){
            //您的客户端已退出，请及时检查，客户端id：${deviceid},机器人昵称：${devicename}
            AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
            alarmMsgFeignDto.setMerId(tbToken.getMerId());
            alarmMsgFeignDto.setType(SysMsgTypeEnum.DOWNLOAD_ORDER_LIMIT.getValue()); //客户端退出
            //消息
            JSONObject ext = new JSONObject();
            ext.put("user", tbToken.getUserName());
            Merchant merchant = merchantMapper.selectById(tbToken.getMerId());
            if(merchant != null){
                ext.put("phone", merchant.getMobile());
            }
            alarmMsgFeignDto.setExt(ext.toJSONString());
//            UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//            logger.info("---淘宝订单下载限流报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

            //2024-01-09修改成直接发送MQ
            noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

        }else{
            logger.info("---淘宝订单下载限流报销消息出现错误--会员id不存在，tbTokenUserId={}", sendAlarmMsgTbOrderDownloadLimitDto.getTbTokenUserId());
        }

    }

    /**
     * 远程调用发送个人微信会员消息
     * @author liuqi
     * @date 2022/11/23 11:38
     * @param wechantUserSendMsgDto
     * @return null
     */
    public void wechatUserSendMsg(WechantUserSendMsgDto wechantUserSendMsgDto){

        if(StringUtils.isBlank(wechantUserSendMsgDto.getSecret())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请上传密钥");
        }

        if(!uzaiConsoleSysConfig.getRemoteApiSecret().equals(wechantUserSendMsgDto.getSecret())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "密钥不正确");
        }

        if(wechantUserSendMsgDto.getId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户ID参数不能为空");
        }

        Long merId = wechantUserSendMsgDto.getMerId();
        if(merId == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商id参数不能为空");
        }

        WechatUser wechatUser  = wechatUserMapper.selectById(wechantUserSendMsgDto.getId(), wechantUserSendMsgDto.getMerId());

        if(wechatUser == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户不存在");
        }

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(wechatUser.getDeviceUniqueId(), wechatUser.getDeviceType(), wechantUserSendMsgDto.getMerId());
        if(device == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户绑定的机器人id不存在");
        }

        if(wechantUserSendMsgDto.getMessage() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "发送消息为空");
        }

        SendMsgInfo sendMsgInfo = JSONObject.parseObject(wechantUserSendMsgDto.getMessage(), SendMsgInfo.class);
        if(sendMsgInfo == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "发送消息为空");
        }

        if(sendMsgInfo.getType() == 0){ //发送文本
            //调用API服务发送消息
            // TODO: 2021/9/4  发送消息
            //发送MQ消息
            MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceType(device.getRecvmsgType());
            msgDto.setDeviceUniqueId(wechatUser.getDeviceUniqueId());
            msgDto.setMerId(wechatUser.getMerId());
            msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
            NoticeMsgDto  noticeMsgDto = new NoticeMsgDto();
            noticeMsgDto.setContent(sendMsgInfo.getContent());
            noticeMsgDto.setBizUserId(wechatUser.getBizUserId());
            noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
            noticeMsgDto.setGroupId(null);
            noticeMsgDto.setNickName(wechatUser.getNickName());
            noticeMsgDto.setMsgSource(1);
            noticeMsgDto.setDelay(wechantUserSendMsgDto.getDelay());
            noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
            msgDto.setContent(noticeMsgDto);
            msgDto.setDelay(wechantUserSendMsgDto.getDelay());
            noticeMsgPushProducerService.sendMessage(msgDto);
        }else if(sendMsgInfo.getType() == 5){
            MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
            msgDto.setDeviceType(device.getRecvmsgType());
            msgDto.setDeviceUniqueId(wechatUser.getDeviceUniqueId());
            msgDto.setId(IdWorker.getId());
            msgDto.setMerId(merId);
            msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
            JSONObject cardVo = new JSONObject();
            cardVo.put("title", sendMsgInfo.getTitle());
            cardVo.put("desc", sendMsgInfo.getDesc());
            cardVo.put("imageUrl", sendMsgInfo.getImageUrl());
            cardVo.put("url", sendMsgInfo.getUrl());
            String cardStr = JSONObject.toJSONString(cardVo);
            NoticeMsgDto noticeMsgDto = new NoticeMsgDto();
            noticeMsgDto.setBizUserId(wechatUser.getBizUserId());
            noticeMsgDto.setGroupId(null);
            noticeMsgDto.setContent(cardStr);
            noticeMsgDto.setContentType(MessageTypeEnum.MT_URL_CARD.getValue());
            noticeMsgDto.setReqId(null);
            noticeMsgDto.setMsgBizType(null);
            noticeMsgDto.setDelay(wechantUserSendMsgDto.getDelay());
            msgDto.setContent(noticeMsgDto);
            msgDto.setDelay(wechantUserSendMsgDto.getDelay());
            noticeMsgPushProducerService.sendMessage(msgDto);
        }else{
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "暂不支持该类型消息发送");
        }
    }

    /**
     * 远程调用修改个人微信会员备注和标签
     * @author liuqi
     * @date 2022/11/23 11:38
     * @param wechantUserUpdateInfoDto
     * @return null
     */
    public void wechatUserUpdateInfo(WechantUserUpdateInfoDto wechantUserUpdateInfoDto){

        if(StringUtils.isBlank(wechantUserUpdateInfoDto.getSecret())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请上传密钥");
        }

        if(!uzaiConsoleSysConfig.getRemoteApiSecret().equals(wechantUserUpdateInfoDto.getSecret())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "密钥不正确");
        }

        if(wechantUserUpdateInfoDto.getId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户ID参数不能为空");
        }

        Long merId = wechantUserUpdateInfoDto.getMerId();
        if(merId == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商id参数不能为空");
        }

        WechatUser wechatUser  = wechatUserMapper.selectById(wechantUserUpdateInfoDto.getId(), wechantUserUpdateInfoDto.getMerId());

        if(wechatUser == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户不存在");
        }

        //标签
        List<String> addTagsList = wechantUserUpdateInfoDto.getTagsArr();
        String tagsStr = Tools.getStrEmpty(JSONObject.toJSONString(addTagsList));
        if(!tagsStr.equals(Tools.getStrEmpty(wechatUser.getTags()))){
            wechatUser.setTags(Tools.getStrEmpty(JSONObject.toJSONString(addTagsList)));
        }

        //是否修改备注
        Boolean setRemarkFlag = false;
        if(!Tools.getStr(wechantUserUpdateInfoDto.getRemark()).equals(Tools.getStr(wechatUser.getRemark()))){ //修改了备注
            //备注
            wechatUser.setRemark(wechantUserUpdateInfoDto.getRemark());
            setRemarkFlag = true;
        }

        //修改微信用户详情信息
        wechatUserMapper.updateById(wechatUser);

        //是否修改了用户备注，如果修改了，则发送MQ同步手机微信好友，
        if(setRemarkFlag){
            //查询机器人
            DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wechatUser.getDeviceUniqueId(), wechantUserUpdateInfoDto.getMerId());
            if(deviceWechatInfo != null){
                //发送MQ消息
                MsgDto<SetUserRemarkDto> msgDto = new MsgDto<>();
                SetUserRemarkDto setUserRemarkDto = new SetUserRemarkDto();
                msgDto.setContent(setUserRemarkDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceUniqueId(wechatUser.getDeviceUniqueId());
                msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                msgDto.setMerId(wechatUser.getMerId());
                msgDto.setMsgType(MessageFuncEnum.SET_USER_REMARK.getValue());
                setUserRemarkDto.setWxid(wechatUser.getBizUserId());
                setUserRemarkDto.setRemark(Tools.getStr(wechatUser.getRemark()));
                noticeMsgPushProducerService.setUserRemark(msgDto);
            }
        }
    }

    /**
     * 远程调用修改个人微信会员客户端
     * @author liuqi
     * @date 2022/11/23 11:38
     * @param wechantUserUpdateDeviceDto
     * @return null
     */
    public void wechatUserUpdateDevice(WechantUserUpdateDeviceDto wechantUserUpdateDeviceDto){

        if(StringUtils.isBlank(wechantUserUpdateDeviceDto.getSecret())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请上传密钥");
        }

        if(!uzaiConsoleSysConfig.getRemoteApiSecret().equals(wechantUserUpdateDeviceDto.getSecret())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "密钥不正确");
        }

        Long id = wechantUserUpdateDeviceDto.getId();
        if(id == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户ID参数不能为空");
        }

        Long merId = wechantUserUpdateDeviceDto.getMerId();
        if(merId == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商id参数不能为空");
        }

        WechatUser wechatUser  = wechatUserMapper.selectById(wechantUserUpdateDeviceDto.getId(), wechantUserUpdateDeviceDto.getMerId());

        if(wechatUser == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户不存在");
        }

        //新的机器人
        Long deviceUniqueIdNew = wechantUserUpdateDeviceDto.getDeviceUniqueIdNew();
        if(deviceUniqueIdNew == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入新机器人id");
        }
        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(deviceUniqueIdNew, merId);
        if(deviceWechatInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人不存在");
        }

        //新的会员类型
        Long userTypeIdNew = wechantUserUpdateDeviceDto.getUserTypeIdNew();
        if(userTypeIdNew == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入新的会员类型");
        }
        UserType userTypeNew = userTypeMapper.selectById(userTypeIdNew, merId);
        if(userTypeNew == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新会员类型不存在或者已经删除");
        }

        if(Tools.getInteger(wechatUser.getIdentity()).intValue() != Tools.getInteger(userTypeNew.getIdentity()).intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新会员类型身份与该会员身份不一样");
        }

        //修改会员默认客户端
        UpdateDefaultClientPersonal updateDefaultClientPersonal  = new UpdateDefaultClientPersonal();
        updateDefaultClientPersonal.setMerId(merId);
        updateDefaultClientPersonal.setId(id);
        updateDefaultClientPersonal.setDeviceUniqueIdNew(deviceUniqueIdNew);
        updateDefaultClientPersonal.setUserTypeIdNew(userTypeIdNew);
        wechatUserMapper.updateDefaultClientPersonal(updateDefaultClientPersonal);
    }

    /**
     * 账房查询支付链接接口
     * @author liuqi
     * @date 2022/11/23 11:38
     * @param cashierAuthpayContentDto
     * @return null
     */
    public CashierAuthpayContentVo getCashierAuthpayContent(CashierAuthpayContentDto cashierAuthpayContentDto){

        CashierAuthpayContentVo cashierAuthpayContentVo = new CashierAuthpayContentVo();
        UzaiRespVo<String> uzaiRespVo = null;

        if(Tools.getInteger(cashierAuthpayContentDto.getType()).intValue() == 2){
            uzaiRespVo = uzaiCashierAdminFeignService.alipayRechargesGetbody(cashierAuthpayContentDto);
        }else{
            uzaiRespVo = uzaiCashierAdminFeignService.getCachierAuthpayContent(cashierAuthpayContentDto);
        }

        logger.info("--调用账房查询查询支付结果结果---para={},result={}", JSONObject.toJSONString(cashierAuthpayContentDto), JSONObject.toJSONString(uzaiRespVo));

        if(uzaiRespVo.getCode() == 200){
            cashierAuthpayContentVo.setData(uzaiRespVo.getData());
        }else{
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
        return cashierAuthpayContentVo;
    }

    /**
     * 朋友圈查询今日合集接口
     * @author liuqi
     * @date 2022/11/23 11:38
     * @param pyqTodySendListDto
     * @return null
     */
    public List<PyqJobDetailVo> pyqTodaySendList(PyqTodySendListDto pyqTodySendListDto){
        List<PyqJobDetailVo> pyqJobDetailVoList = new ArrayList<>();

        if(pyqTodySendListDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入朋友圈id");
        }

        if(pyqTodySendListDto.getMerId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入运营商id");
        }

        String uzai_pyq_job_detail = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_PYQ_JOB_DETAIL, pyqTodySendListDto.getMerId());

        Map<String,Object> pyqJobDetailEsMap = elasticsearchUtilGroupMsg.searchDataById(uzai_pyq_job_detail, String.valueOf(pyqTodySendListDto.getId()), null);

        PyqJobDetail pyqJobDetail_current = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pyqJobDetailEsMap)), PyqJobDetail.class);
        if(pyqJobDetail_current != null){ //该朋友圈id不存在
            Integer sendTime = pyqJobDetail_current.getSendTime();
            String sendTime_day = Tools.getDateFormat(new Date( sendTime * 1000L),"yyyy-MM-dd");
            int sendTimeStart = DateUtil.getStrTime(sendTime_day + " 00:00:00");
            int sendTimeEnd = DateUtil.getStrTime(sendTime_day + " 23:59:59");

            //ES查询
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

            //运营商ID
            boolQuery.must(QueryBuilders.termQuery("merId", Tools.getLong(pyqTodySendListDto.getMerId())));

            //状态(已发送)
            boolQuery.must(QueryBuilders.termQuery("status", PyqJobDetailStatusEnum.SENDED.getValue()));

            //机器人唯一id
            boolQuery.must(QueryBuilders.termQuery("deviceUniqueId", pyqJobDetail_current.getDeviceUniqueId()));

            //查询开始时间和结束时间段
            boolQuery.must(QueryBuilders.rangeQuery("sendTime").gte(sendTimeStart).lte(sendTimeEnd));

            //查询结束时间
            //boolQuery.must(QueryBuilders.rangeQuery("sendTime").lte(sendTimeEnd));

            searchSourceBuilder.query(boolQuery);
            //排序
            searchSourceBuilder.sort("sendTime", SortOrder.DESC);

            PyqJobDetailQuery pyqJobDetailQuery = new PyqJobDetailQuery();
            pyqJobDetailQuery.setMerId(pyqTodySendListDto.getMerId());
            pyqJobDetailQuery.setCurrent(1);
            pyqJobDetailQuery.setSize(100);
            ESResult esResult = elasticsearchUtilGroupMsg.searchListData(uzai_pyq_job_detail, searchSourceBuilder, pyqJobDetailQuery.getSize(), pyqJobDetailQuery.getFromIndex(), null, null, null, pyqJobDetailQuery.getMerId());
            List<Map<String, Object>> dataList = esResult.getDataList();
            if(dataList != null && dataList.size() > 0){
                for (Map<String, Object> dataMp :dataList) {
                    PyqJobDetail pyqJobDetail  = JSONObject.parseObject(JSONObject.toJSONString(dataMp), PyqJobDetail.class);
                    PyqJobDetailVo pyqJobDetailVo = new PyqJobDetailVo();
                    if(pyqJobDetail != null){
                        BeanUtils.copyProperties(pyqJobDetail, pyqJobDetailVo);

                        //封装图片
                        if(StringUtils.isNotBlank(pyqJobDetailVo.getFeedMediaList())){
                            List<FeedMedia> feedMediaList = JSONObject.parseArray(pyqJobDetailVo.getFeedMediaList(), FeedMedia.class);
                            if(feedMediaList != null && feedMediaList.size() > 0){
                                List<String> imgList = new ArrayList<>();
                                if(Tools.getInteger(pyqJobDetailVo.getAttachType()).intValue() == 2){
                                    for (FeedMedia feedMedia : feedMediaList) {
                                        imgList.add(feedMedia.getUrl());
                                    }
                                }else{
                                    for (FeedMedia feedMedia : feedMediaList) {
                                        imgList.add(feedMedia.getCover());
                                    }
                                }
                                pyqJobDetailVo.setImgs(JSONObject.toJSONString(imgList));
                            }
                        }else{ //旧版接口
                            if(StringUtils.isNotBlank(pyqJobDetailVo.getImgs())){
                                List<String> imgList = JSONObject.parseArray(pyqJobDetailVo.getImgs(), String.class);
                                pyqJobDetailVo.setImgs(JSONObject.toJSONString(imgList));
                            }
                        }

                        //视频号朋友圈，如果图片为空，封装首图
                        if(StringUtils.isBlank(pyqJobDetailVo.getImgs())){
                            if(AttachTypeEnum.SHIPINHAO.getValue().intValue() == Tools.getInteger(pyqJobDetailVo.getAttachType()).intValue()){
                                List<String> imgList = new ArrayList<>();
                                imgList.add(Const.PyqFirstImg.SHIPINHAO);
                                pyqJobDetailVo.setImgs(JSONObject.toJSONString(imgList));
                            }
                        }

                        if(pyqJobDetailVo.getDeviceUniqueId() != null){
                            String deviceType = null;
                            DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getById(pyqJobDetailVo.getDeviceType());
                            if(deviceTypeEnum != null){
                                deviceType = deviceTypeEnum.getKey();
                            }
                            Device device = deviceService.findDeviceInfoByDeviceUniqueId(pyqJobDetailVo.getDeviceUniqueId(), deviceType, pyqJobDetail.getMerId());
                            if(device != null){
                                DeviceInfoVo deviceInfoVo = new DeviceInfoVo();
                                BeanUtils.copyProperties(device, deviceInfoVo);
                                pyqJobDetailVo.setDeviceInfoVo(deviceInfoVo);
                            }
                        }
                        pyqJobDetailVoList.add(pyqJobDetailVo);
                    }
                }
            }
        }
        return pyqJobDetailVoList;
    }

    /**
     * 朋友圈查询明细
     * @author liuqi
     * @date 2022/11/23 11:38
     * @param remoteApiPyqDetailIdDt
     * @return null
     */
     public PyqJobDetailVo findPyqDetail(RemoteApiPyqDetailIdDto remoteApiPyqDetailIdDt){
         if(remoteApiPyqDetailIdDt.getId() == null){
             throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
         }
         if(remoteApiPyqDetailIdDt.getMerId() == null){
             throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商id不能为空");
         }

         PyqJobDetailIdDto pyqJobDetailIdDto = new PyqJobDetailIdDto();
         pyqJobDetailIdDto.setMerId(remoteApiPyqDetailIdDt.getMerId());
         pyqJobDetailIdDto.setId(String.valueOf(remoteApiPyqDetailIdDt.getId()));

         return pyqJobDetailService.findPyqJobDetail(pyqJobDetailIdDto);
     }


    /**
     * 报表面板粉丝价值报表
     * @author liuqi
     * @date 2022/11/23 11:38
     * @param reportPanelFansValueReportQuery
     * @return null
     */
    public Page<ReportBanelFansValueReportVo> reportbanelFansValueReprot(ReportPanelFansValueReportQuery reportPanelFansValueReportQuery){

        //运营商id
        Long merId = reportPanelFansValueReportQuery.getMerId();
        if(merId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商id不能为空");
        }

        //限流处理--5秒一次
        String key = "request:reportbanelFansValueReprot-merId=" + merId;
        boolean inRateLimit = ratelimitService.inRateLimit(key , 1, 5);
        if (!inRateLimit){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请求频繁，请稍后在统计");
        }
        //报表面板id
        Long reportBanelId = reportPanelFansValueReportQuery.getReportBanelId();
        if(reportBanelId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "报表面板id不能为空");
        }
        //报表面板
        ReportPanel reportPanel = reportPanelMapper.selectById(reportBanelId, merId);
        if(reportPanel == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该报表面板不存在或者已删除");
        }

        //报表面板参数JSON对象
        JSONObject jsonObject_para = JSONObject.parseObject(reportPanel.getParaData());
        if(jsonObject_para == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该报表面板未设置查询条件数据");
        }
        //报表面板设备方案
        String deviceType_banel = jsonObject_para.getString("deviceType");
        if(StringUtils.isBlank(deviceType_banel)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该报表面板未设置设备方案");
        }
        //报表面板机器人列表
        List<Long> deviceUniqueIdList_banel = JSONObject.parseArray(jsonObject_para.getString("deviceUniqueIdList"), Long.class);
        if(deviceUniqueIdList_banel == null || deviceUniqueIdList_banel.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该报表面板设置的未设置查询机器人");
        }
        //报表面板显示字段
        JSONObject jsonObject_show = JSONObject.parseObject(reportPanel.getShowData());
        if(jsonObject_show == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该报表面板未设置显示字段数据");
        }
        //报表面板机器人
        List<String> showFieldList_banel = JSONObject.parseArray(jsonObject_show.getString("showFieldList"), String.class);
        if(showFieldList_banel == null || showFieldList_banel.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该报表面板设置的未设置显示字段");
        }
        //报表面板开始时间
        Integer queryStartTime_banel = jsonObject_para.getInteger("queryStartTime");
        Integer queryEndTime_banel = jsonObject_para.getInteger("queryEndTime");
        boolean noHasEndTime = Objects.isNull(queryEndTime_banel) || 0 == queryEndTime_banel;
        if(queryStartTime_banel == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该报表面板未设置查询开始时间");
        }


        //查询条件
        //条件设备类型(如果为空，则查询面板中设备方案，如果不为空，则需要判断是否跟面板的设备方案一样)
        String deviceType = reportPanelFansValueReportQuery.getDeviceType();
        if(StringUtils.isBlank(deviceType)){
            reportPanelFansValueReportQuery.setDeviceType(deviceType_banel);
        }else{
            //设备方案不相等
            if(!deviceType_banel.equals(deviceType)){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "查询的设备类型跟报表面板的不一样");
            }
        }

        //条件机器人(如果为空，则查询面板中机器人，如果不为空，则需要判断查询机器人是否都在面板机器人当中)
        List<Long> deviceUniqueIdList = reportPanelFansValueReportQuery.getDeviceUniqueIdList();
        if(deviceUniqueIdList == null || deviceUniqueIdList.size() == 0){
            reportPanelFansValueReportQuery.setDeviceUniqueIdList(deviceUniqueIdList_banel);
        }else{
            if(!deviceUniqueIdList_banel.containsAll(deviceUniqueIdList)){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "查询机器人不在该报表面板设置的机器人列表中");
            }
        }


        //条件查询开始时间
        Integer queryStartTime = reportPanelFansValueReportQuery.getQueryStartTime();
        if(queryStartTime == null){
            //需要判断面板开始时间，如果小于今天凌晨0点的时间，则已今天凌晨0点作为开始时间，否则就已面板开始时间作为查询时间
            //获取今天凌晨0点的时间搓
            //获取当前得月份
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String today_yyyyMmdd = sdf.format(new Date());
            String today_str_0 = today_yyyyMmdd + " 00:00:00";
            int today_0 = DateUtil.getStrTime(today_str_0);
            if(queryStartTime_banel < today_0){
                queryStartTime = today_0;
            }else{
                queryStartTime = queryStartTime_banel;
            }
            reportPanelFansValueReportQuery.setQueryStartTime(queryStartTime);
        }

        //条件查询结束时间,如果为空，则默认为当前时间
        Integer queryEndTime = reportPanelFansValueReportQuery.getQueryEndTime();
        if(queryEndTime == null){
            queryEndTime = noHasEndTime ? DateUtil.getNowTime() : queryEndTime_banel;
            reportPanelFansValueReportQuery.setQueryEndTime(queryEndTime);
        } else {
            if (!noHasEndTime) {
                if (queryEndTime > queryEndTime_banel) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "结束时间已超限");
                }
            }
        }

        if(queryEndTime.intValue() < queryStartTime.intValue()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "结束时间不能早于开始时间");
        }

        if(queryEndTime.intValue()- queryStartTime.intValue() > 31*24*3600){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最多只能查询31天的报表");
        }

        int now = DateUtil.getNowTime();
        if(now - queryStartTime.intValue() > 90*24*3600){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最早只能查询90天以内的报表");
        }

        //查询开始时间不能早于面板的查询开始时间
        if(queryStartTime < queryStartTime_banel){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "查询开始时间不能早于面板的查询开始时间");
        }

        //返回到页面分页对象
        Page<ReportBanelFansValueReportVo> pageVo = new Page<>();
        reportPanelFansValueReportQuery.convert(pageVo);
        //新建返回到页面的LIST对象
        List<ReportBanelFansValueReportVo> reportBanelFansValueReportVoList = new ArrayList<>();

        //查询粉丝价值报表
        FansValueReportQuery fansValueReportQuery = new FansValueReportQuery();
        BeanUtils.copyProperties(reportPanelFansValueReportQuery, fansValueReportQuery);
        fansValueReportQuery.setDeviceUniqueIdList(reportPanelFansValueReportQuery.getDeviceUniqueIdList());
        fansValueReportQuery.setMerId(reportPanelFansValueReportQuery.getMerId());
        //粉丝价值报表统计数据
        Page<FansValueReportVo> fansValueReportVoPage = fansValueReportService.fansValueReport(fansValueReportQuery);
        List<FansValueReportVo> fansValueReportVoList = fansValueReportVoPage.getRecords();
        if(fansValueReportVoList != null && fansValueReportVoList.size() > 0){
            for (FansValueReportVo fansValueReportVo : fansValueReportVoList) {
                ReportBanelFansValueReportVo reportBanelFansValueReportVo = new ReportBanelFansValueReportVo();
                reportBanelFansValueReportVoList.add(reportBanelFansValueReportVo);
                //封装此报表面板的显示字段值
                for (String showField : showFieldList_banel) {

                    //反射拿到的值
                    Object object_value = null;
                    //反射报表查询出的对象
                    Class cls_dto = fansValueReportVo.getClass();
                    Field field_dto = null;
                    try {
                        field_dto = cls_dto.getDeclaredField(showField);
                        field_dto.setAccessible(true);//设置允许访问
                        object_value = field_dto.get(fansValueReportVo);
                    } catch (Exception e) {
                    }

                    ////在通过反射塞回面板报表对象中
                    Class cls_vo = reportBanelFansValueReportVo.getClass();
                    Field field_vo = null;
                    try {
                        field_vo = cls_vo.getDeclaredField(showField);
                        field_vo.setAccessible(true);//设置允许访问
                        field_vo.set(reportBanelFansValueReportVo, object_value);
                    } catch (Exception e) {
                        logger.error(e.getMessage(),e);
                    }
                }
            }
        }

        pageVo.setRecords(reportBanelFansValueReportVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 更新微信群ES缓存中的群配置方案id
     * @author liuqi
     * @date 2022/11/23 11:38
     * @param
     * @return null
     */
    @Async("taskExecutor")
    public void updateManagePlanIdToEs(){

//        //限流判断(2个小时之内执行一次)
//        String inRateLimit_key = "-updateManagePlanIdToEs-";
//        boolean inRateLimit = ratelimitService.inRateLimit(inRateLimit_key,1,3600 * 2);
//        if (!inRateLimit){
//            //logger.info("---inRateLimit false. deviceUniqueId={}", deviceAuth.getDeviceUniqueId());
//            //return;
//        }
//
//        int now = DateUtil.getNowTime();
//
//        //个人微信群配置方案
//        WxqGroupManagePlanQuery wxqGroupManagePlanQuery_private = new WxqGroupManagePlanQuery();
//        //查询机器人已经到期
//        Page<WxqGroupManagePlan> page_private = new Page<>();
//        page_private.setCurrent(1);//只查第一页
//        page_private.setSize(10); //每页查询10个
//        page_private.addOrder(OrderItem.asc("id"));//默认id升序
//        Long idStart_private = 0L;
//        List<WxqGroupManagePlan> wxqGroupManagePlanList = wxqGroupManagePlanMapper.findByList(page_private, wxqGroupManagePlanQuery_private);
//        while (wxqGroupManagePlanList != null && wxqGroupManagePlanList.size() > 0){
//            for (WxqGroupManagePlan wxqGroupManagePlan : wxqGroupManagePlanList) {
//                if(wxqGroupManagePlan.getId().longValue() > idStart_private.longValue()){
//                    idStart_private = wxqGroupManagePlan.getId();
//                }
//                //查询微信群
//                String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, wxqGroupManagePlan.getMerId());
//                //微信群主键id：merId_deviceId_wxid
//                String groupId = wxqGroupManagePlan.getMerId() + "_" + wxqGroupManagePlan.getDeviceId() + "_" + wxqGroupManagePlan.getWxid();
//                Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, groupId, null);
//                EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWxContacts.class);
//                if(esWxContacts == null){ //不存在，则表示该群不存在，则需要自动清理该管理方案微信群
//                    wxqGroupManagePlanMapper.deleteById(wxqGroupManagePlan.getId(), wxqGroupManagePlan.getMerId());
//                    //删除缓存中的微信群管理方案key
//                    String redisKey_wxgroup_manageplan = String.format(RedisCacheKeyEnum.WXGROUP_MANAGEPLAN_CONFIG.getKey(), wxqGroupManagePlan.getMerId(), wxqGroupManagePlan.getDeviceId(), wxqGroupManagePlan.getWxid());
//                    redisTemplate.delete(redisKey_wxgroup_manageplan);
//                }else{
//                    //群管理方案id
//                    Long managePlanId = wxqGroupManagePlan.getManagePlanId();
//                    ConfigPlan configPlan = configPlanMapper.selectById(managePlanId,wxqGroupManagePlan.getMerId());
//                    if(configPlan != null){
//                        //修改ES的群管理配置方案id
//                        //修改明细状态
//                        JSONObject jsonObject = new JSONObject();
//                        jsonObject.put("managePlanId", managePlanId); //修改配置方案
//                        jsonObject.put("updateTime", now);
//                        elasticsearchUtilGroupMsg.updateDataById(jsonObject, uzai_wx_contacts, esWxContacts.getId());
//                    }else{//配置方案不存在，则清空群管理配置方案信息
//                        esWxContacts.setManagePlanId(null);
//                        esWxContacts.setUpdateTime(now);
//                        elasticsearchUtilGroupMsg.addData(esWxContacts, uzai_wx_contacts, esWxContacts.getId());
//                    }
//                }
//            }
//            wxqGroupManagePlanQuery_private.setIdStart(idStart_private);
//            wxqGroupManagePlanList = wxqGroupManagePlanMapper.findByList(page_private, wxqGroupManagePlanQuery_private);
//        }
//
//        //企业微信群配置方案
//        WxqWorkGroupManagePlanQuery wxqWorkGroupManagePlanQuery_work = new WxqWorkGroupManagePlanQuery();
//        //查询机器人已经到期
//        Page<WxqWorkGroupManagePlan> page_work = new Page<>();
//        page_work.setCurrent(1);//只查第一页
//        page_work.setSize(10); //每页查询10个
//        page_work.addOrder(OrderItem.asc("id"));//默认id升序
//        Long idStart_work = 0L;
//        List<WxqWorkGroupManagePlan> wxqWorkGroupManagePlanList = wxqWorkGroupManagePlanMapper.findByList(page_work, wxqWorkGroupManagePlanQuery_work);
//        while (wxqWorkGroupManagePlanList != null && wxqWorkGroupManagePlanList.size() > 0){
//            for (WxqWorkGroupManagePlan wxqWorkGroupManagePlan : wxqWorkGroupManagePlanList) {
//                if(wxqWorkGroupManagePlan.getId().longValue() > idStart_work.longValue()){
//                    idStart_work = wxqWorkGroupManagePlan.getId();
//                }
//                //查询微信群
//                String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxqWorkGroupManagePlan.getMerId());
//                //微信群主键id：merId_deviceId_wxid
//                String groupId = wxqWorkGroupManagePlan.getMerId() + "_" + wxqWorkGroupManagePlan.getDeviceId() + "_" + wxqWorkGroupManagePlan.getGroupId();
//                Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, groupId, null);
//                EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
//                if(esWorkWxGroupInfo == null){ //不存在，则表示该群不存在，则需要自动清理该管理方案微信群
//                    wxqWorkGroupManagePlanMapper.deleteById(wxqWorkGroupManagePlan.getId(), wxqWorkGroupManagePlan.getMerId());
//                    //删除缓存中的微信群管理方案key
//                    String redisKey_wxgroup_manageplan = String.format(RedisCacheKeyEnum.WXGROUP_WORK_MANAGEPLAN_CONFIG.getKey(), wxqWorkGroupManagePlan.getMerId(), wxqWorkGroupManagePlan.getDeviceId(), wxqWorkGroupManagePlan.getGroupId());
//                    redisTemplate.delete(redisKey_wxgroup_manageplan);
//                }else{
//                    //群管理方案id
//                    Long managePlanId = wxqWorkGroupManagePlan.getManagePlanId();
//                    ConfigPlan configPlan = configPlanMapper.selectById(managePlanId, wxqWorkGroupManagePlan.getMerId());
//                    if(configPlan != null){
//                        //修改ES的群管理配置方案id
//                        JSONObject jsonObject = new JSONObject();
//                        jsonObject.put("managePlanId", managePlanId); //修改配置方案
//                        jsonObject.put("updateTime", now);
//                        elasticsearchUtilGroupMsg.updateDataById(jsonObject, uzai_workwx_group_info, esWorkWxGroupInfo.getId());
//                    }else{
//                        esWorkWxGroupInfo.setManagePlanId(null);
//                        esWorkWxGroupInfo.setUpdateTime(now);
//                        elasticsearchUtilGroupMsg.addData(esWorkWxGroupInfo, uzai_workwx_group_info, esWorkWxGroupInfo.getId());
//                    }
//                }
//            }
//            wxqWorkGroupManagePlanQuery_work.setIdStart(idStart_work);
//            wxqWorkGroupManagePlanList = wxqWorkGroupManagePlanMapper.findByList(page_work, wxqWorkGroupManagePlanQuery_work);
//        }
//
//        //执行完删除限流
//        redisTemplate.delete(inRateLimit_key);
    }

    /**
     * 根据商品id清除自动发送朋友圈历史记录
     * @author liuqi
     * @date 2022/11/23 11:38
     * @param
     * @return null
     */
    public void deletePyqAutoSendByGoodsid(PyqAutoSendDeleteDto pyqAutoSendDeleteDto){
        if(pyqAutoSendDeleteDto.getGoodsid() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入商品id");
        }
        pyqAutoSendMapper.deleteByGoodsid(pyqAutoSendDeleteDto.getGoodsid());

        logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_AUTO_VALUE,
                1157181383497326594L, 0, null,
                "", 0L,
                "远程调用了清除朋友圈自动发送商品历史记录：商品主键id:" + pyqAutoSendDeleteDto.getGoodsid())));

    }

    @Override
    public Object dataPanelInfo(DataPanelRemoteQuery query) {


        Long merId = query.getMerId();
        if (Objects.isNull(query.getMerId())) {
            throw new BusinessException("运营商id不能为空");
        }

        //报表面板id
        Long reportPanelId = query.getReportBanelId();
        if (reportPanelId == null) {
            throw new BusinessException("数据面板id不能为空");
        }

        ReportPanel reportPanel = dataPanelMapper.selectById(reportPanelId, merId);
        if (Objects.isNull(reportPanel)) {
            throw new BusinessException("数据面板不存在");
        }
        BaseDataPanelService baseDataPanelService = dataPanelHolder.matchDataPanel(reportPanel.getType());
        baseDataPanelService.checkDataPanel(reportPanel);

        JSONObject data = JSONObject.parseObject(reportPanel.getParaData());
        String deviceType = data.getString("deviceType");
        //判断设备类型是否一致
        if (StringUtils.isBlank(query.getDeviceType())) {
            query.setDeviceType(deviceType);
        } else {
            //设备方案不相等
            if (!deviceType.equals(query.getDeviceType())) {
                throw new BusinessException("查询的设备类型跟数据面板不一致");
            }
        }

        //条件机器人(如果为空，则查询面板中机器人，如果不为空，则需要判断查询机器人是否都在面板机器人当中)
        List<Long> deviceUniqueIdList = data.getJSONArray("deviceUniqueIdList").toJavaList(Long.class);
        if (ObjectUtils.isEmpty(query.getDeviceUniqueIdList())) {
            query.setDeviceUniqueIdList(deviceUniqueIdList);
        } else {
            for (Long deviceUniqueId : query.getDeviceUniqueIdList()) {
                if (!deviceUniqueIdList.contains(deviceUniqueId)) {
                    throw new BusinessException("查询机器人不在数据面板设置的机器人列表中");
                }
            }
        }
        query.setDataPanel(reportPanel);

        /*Integer queryStartTime = data.getInteger("queryStartTime");
        //条件查询开始时间
        if (Objects.isNull(query.getQueryStartTime())) {
            //需要判断面板开始时间，如果小于今天凌晨0点的时间，则已今天凌晨0点作为开始时间，否则就已面板开始时间作为查询时间
            //获取今天凌晨0点的时间搓
            //获取当前得月份
            int todayBegin = (int) (cn.hutool.core.date.DateUtil.beginOfDay(DateTime.now()).getTime() / 1000);
            query.setQueryStartTime(queryStartTime < todayBegin ? todayBegin : queryStartTime);
        }

        //条件查询结束时间,如果为空，则默认为当前时间
        query.setQueryEndTime(Objects.isNull(query.getQueryEndTime()) ? DateUtil.getNowTime() : query.getQueryEndTime());*/

        /*if (query.getQueryEndTime() < queryStartTime) {
            throw new BusinessException("结束时间不能早于开始时间");
        }

        if (query.getQueryEndTime() - query.getQueryStartTime() > 31 * 24 * 3600) {
            throw new BusinessException("最多只能查询31天的数据");
        }

        int now = DateUtil.getNowTime();
        if (now - queryStartTime > 90 * 24 * 3600) {
            throw new BusinessException("最早只能查询90天以内的数据");
        }

        //查询开始时间不能早于面板的查询开始时间
        if (query.getQueryStartTime() < queryStartTime) {
            throw new BusinessException("查询开始时间不能早于面板的查询开始时间");
        }*/

        query.setDeviceType(StringUtils.isBlank(query.getDeviceType()) ? reportPanel.getDeviceType() : query.getDeviceType());
        return baseDataPanelService.remoteDataQuery(query);
    }

    /**
     * 更新淘宝联盟的mm_user_id
     * @author liuqi
     * @date 2022/11/23 11:38
     * @param
     * @return null
     */
    public void updateTbTokenMMUserId(){
        //已经到期
        TbTokenQuery tbTokenQuery = new TbTokenQuery();

        //查询机器人已经到期
        Page<TbToken> page = new Page<>();
        page.setCurrent(1);//只查第一页
        page.setSize(10); //每页查询10个
        page.addOrder(OrderItem.asc("id"));//默认id升序
        Long idStart = 0L;

        List<TbToken> tbTokenList = tbTokenMapper.findByList(page, tbTokenQuery);
        while (tbTokenList != null && tbTokenList.size() > 0){
            for (TbToken tbToken : tbTokenList) {
                if(tbToken.getId().longValue() > idStart.longValue()){
                    idStart = tbToken.getId();
                }
                //限流判断(30秒内判断一次)
                boolean inRateLimit = ratelimitService.inRateLimit("updateTbTokenMMUserId-" + tbToken.getId(),1,30);
                if (!inRateLimit){
                    //logger.info("---inRateLimit false. deviceUniqueId={}", deviceAuth.getDeviceUniqueId());
                    continue;
                }

                String defPid = tbToken.getDefPid();
                if(StringUtils.isNotBlank(defPid)){
                    String[] defPidList = defPid.split("_");
                    if(defPidList != null && defPidList.length == 4){
                        tbToken.setMmUserId(Long.valueOf(defPidList[1])); //获取mmUserId=defPid的第二位
                        tbTokenMapper.update(tbToken);
                    }
                }
            }
            tbTokenQuery.setIdStart(idStart);
            tbTokenList = tbTokenMapper.findByList(page, tbTokenQuery);
        }
    }

    /**
     * 更新清理僵尸粉任务状态
     * @author liuqi
     * @date 2022/11/23 11:38
     * @param
     * @return null
     */
    public void updateZombieFanTaskStatus(@RequestBody ZombieFanTaskUpdateStatusDto zombieFanTaskUpdateStatusDto){

        logger.info("--客户端调用更新清理僵尸粉任务状态接口--dto={}",JSONObject.toJSONString(zombieFanTaskUpdateStatusDto));

        if(zombieFanTaskUpdateStatusDto.getDeviceUniqueId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入机器人唯一id");
        }

        if(zombieFanTaskUpdateStatusDto.getMerId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入运营商id");
        }
        //通过机器人唯一id查询清理僵尸粉任务
        ZombieFanTask zombieFanTask = zombieFanTaskMapper.selectByDeviceUniqueId(zombieFanTaskUpdateStatusDto.getDeviceUniqueId(), zombieFanTaskUpdateStatusDto.getMerId());
        zombieFanTask.setStatus(ZombieFanTaskStatusEnum.DELETING.getId()); //修改成清粉中状态
        zombieFanTask.setUpdateTime(DateUtil.getNowTime());
        zombieFanTaskMapper.updateById(zombieFanTask);
    }

    /**
     * 社群成员加入黑名单
     * @author liuqi
     * @date 2022/11/23 11:38
     * @param
     * @return null
     */
    public void addBlacklistByWxGroup(WxGroupAddBlacklistDto wxGroupAddBlacklistDto){
        logger.info("--客户端社群成员加入黑名单接口--dto={}",JSONObject.toJSONString(wxGroupAddBlacklistDto));

        if(wxGroupAddBlacklistDto.getMerId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入运营商id");
        }

        if(wxGroupAddBlacklistDto.getDeviceUniqueId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入机器人唯一id");
        }

        if(StringUtils.isBlank(wxGroupAddBlacklistDto.getDeviceId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入机器人微信id");
        }

        if(StringUtils.isBlank(wxGroupAddBlacklistDto.getGroupWxid())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入群微信id");
        }

        if(StringUtils.isBlank(wxGroupAddBlacklistDto.getMemberWxid())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入成员微信id");
        }

        //拼接群主键id
        String groupId = wxGroupAddBlacklistDto.getMerId() + "_" + wxGroupAddBlacklistDto.getDeviceId() + "_" + wxGroupAddBlacklistDto.getGroupWxid();
        //成员主键id
        String memberId = wxGroupAddBlacklistDto.getMerId() + "_" + wxGroupAddBlacklistDto.getGroupWxid() + "_" + wxGroupAddBlacklistDto.getMemberWxid();
        WxGroupMemberBlacklistDto wxGroupMemberBlacklistDto = new WxGroupMemberBlacklistDto();
        BeanUtils.copyProperties(wxGroupAddBlacklistDto, wxGroupMemberBlacklistDto);
        wxGroupMemberBlacklistDto.setMerId(wxGroupAddBlacklistDto.getMerId());
        wxGroupMemberBlacklistDto.setGroupId(groupId);
        wxGroupMemberBlacklistDto.setId(memberId);
        wxGroupMemberBlacklistDto.setType(wxGroupAddBlacklistDto.getType());
        wxGroupMemberBlacklistDto.setRange(wxGroupAddBlacklistDto.getRange());
        wxGroupMemberBlacklistDto.setRemark(wxGroupAddBlacklistDto.getRemark());
        wxGroupMemberBlacklistDto.setAllBackFlag(wxGroupAddBlacklistDto.getAllBackFlag());
        wxGroupMemberMemberService.addBlacklist(wxGroupMemberBlacklistDto);
    }

    /**
     * 会员黑名单共享至全网
     * @author liuqi
     * @date 2022/11/23 11:38
     * @param
     * @return null
     */
    public void userBlacklistSharePub(UserBlackListSharePubDto userBlackListSharePubDto){
        logger.info("--会员黑名单共享至全网--dto={}", JSONObject.toJSONString(userBlackListSharePubDto));

        if(userBlackListSharePubDto.getMerId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入运营商id");
        }

        if(StringUtils.isBlank(userBlackListSharePubDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入私有黑名单主键id");
        }

        WechatBlacklistPrvIdDto wechatBlacklistPrvIdDto = new WechatBlacklistPrvIdDto();
        wechatBlacklistPrvIdDto.setId(userBlackListSharePubDto.getId());
        wechatBlacklistPrvIdDto.setMerId(userBlackListSharePubDto.getMerId());

        wechatBlacklistPrvService.shareWechatBlacklistPub(wechatBlacklistPrvIdDto);
    }


    /**
     * 会员黑名单取消至全网
     * @author liuqi
     * @date 2022/11/23 11:38
     * @param
     * @return null
     */
    public void userBlacklistCancelPub(UserBlackListCancelPubDto userBlackListCancelPubDto){
        logger.info("--会员黑名单取消至全网--dto={}", JSONObject.toJSONString(userBlackListCancelPubDto));

        if(userBlackListCancelPubDto.getMerId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入运营商id");
        }

        if(StringUtils.isBlank(userBlackListCancelPubDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入私有黑名单主键id");
        }

        WechatBlacklistPrvIdDto wechatBlacklistPrvIdDto = new WechatBlacklistPrvIdDto();
        wechatBlacklistPrvIdDto.setId(userBlackListCancelPubDto.getId());
        wechatBlacklistPrvIdDto.setMerId(userBlackListCancelPubDto.getMerId());

        wechatBlacklistPrvService.cancelWechatBlacklistPub(wechatBlacklistPrvIdDto);

    }

    /**
     * 会员黑名单移除私有黑名单
     * @author liuqi
     * @date 2022/11/23 11:38
     * @param
     * @return null
     */
    public void userBlacklistDeletePrv(UserBlackListDeletePrvDto userBlackListDeletePrvDto){
        logger.info("--会员黑名单移除私有黑名单--dto={}", JSONObject.toJSONString(userBlackListDeletePrvDto));

        if(userBlackListDeletePrvDto.getMerId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入运营商id");
        }

        if(StringUtils.isBlank(userBlackListDeletePrvDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入私有黑名单主键id");
        }

        WechatBlacklistPrvIdDto wechatBlacklistPrvIdDto = new WechatBlacklistPrvIdDto();
        wechatBlacklistPrvIdDto.setId(userBlackListDeletePrvDto.getId());
        wechatBlacklistPrvIdDto.setMerId(userBlackListDeletePrvDto.getMerId());

        wechatBlacklistPrvService.deleteWechatBlacklistPrv(wechatBlacklistPrvIdDto);
    }

    /**
     * 悠聊分页查询好友请求数据
     * @author liuqi
     * @date 2022/11/23 11:38
     * @param friendRequestByUchatRemoteQuery
     * @return null
     */
    public Page<FriendRequestInfoVo> friendRequestByPage(FriendRequestByUchatRemoteQuery friendRequestByUchatRemoteQuery){
        //新建返回到页面的LIST对象
        List<FriendRequestInfoVo> friendRequestInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<FriendRequestInfoVo> page = new Page<>();
        friendRequestByUchatRemoteQuery.convert(page);
        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        if(friendRequestByUchatRemoteQuery.getMerId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入运营商id");
        }

        if(friendRequestByUchatRemoteQuery.getKefuUserId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入悠聊账号主键id");
        }

        //运营商ID
        boolQuery.must(QueryBuilders.termQuery("merId", Tools.getLong(friendRequestByUchatRemoteQuery.getMerId())));

        //高亮字段
        String highlightField = null;

        //分页查询该子账号关联的机器人没有查询。
        List<Long> deviceUniqueIdList = new ArrayList<>();
        KefuClientQuery kefuClientQuery = new KefuClientQuery();
        kefuClientQuery.setMerId(friendRequestByUchatRemoteQuery.getMerId());
        kefuClientQuery.setKefuUserId(friendRequestByUchatRemoteQuery.getKefuUserId());
        List<KefuClient> kefuClientList = kefuClientMapper.findByList(kefuClientQuery);
        if(kefuClientList == null || kefuClientList.size() == 0){
            return page;
        }

        for (KefuClient kefuClient : kefuClientList) {
            deviceUniqueIdList.add(kefuClient.getDeviceUniqueId());
        }

        //机器人唯一id
        if(deviceUniqueIdList != null && deviceUniqueIdList.size() > 0){
            boolQuery.must(QueryBuilders.termsQuery("deviceUniqueId", deviceUniqueIdList));
        }

        searchSourceBuilder.query(boolQuery);

        //排序
        searchSourceBuilder.sort("status", SortOrder.ASC);
        searchSourceBuilder.sort("reqTime", SortOrder.DESC);

        //判断是否需要脱敏
        ESResult esResult = elasticsearchUtil.searchListData(EsIndexName.UZAI_WECHAT_REQ_USER, searchSourceBuilder, friendRequestByUchatRemoteQuery.getSize(), friendRequestByUchatRemoteQuery.getFromIndex(), null, null, highlightField, friendRequestByUchatRemoteQuery.getMerId());
        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                FriendRequestInfoVo friendRequestInfoVo  = JSONObject.parseObject(JSONObject.toJSONString(dataMp), FriendRequestInfoVo.class);
                friendRequestInfoVoList.add(friendRequestInfoVo);
            }
        }
        //返回到页面分页对象
        page.setRecords(friendRequestInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }

    /**
     * 通过好友请求
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param friendRequestIdListDto
     * @return null
     */
    @Async("taskExecutor")
    public void addFriendRequest(FriendRequestIdListDto friendRequestIdListDto){

        logger.info("悠聊通过好友请求-参数：para={}", JSONObject.toJSONString(friendRequestIdListDto));

        if(friendRequestIdListDto.getMerId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入运营商id");
        }

        friendRequestService.addFriendRequest(friendRequestIdListDto);
    }

    /**
     * 忽略好友请求
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param friendRequestIdListDto
     * @return null
     */
    @Async("taskExecutor")
    public void passFriendRequest(FriendRequestIdListDto friendRequestIdListDto){

        logger.info("悠聊忽略好友请求-参数：para={}", JSONObject.toJSONString(friendRequestIdListDto));

        if(friendRequestIdListDto.getMerId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入运营商id");
        }

        friendRequestService.passFriendRequest(friendRequestIdListDto);
    }

    /**
     * 设置机器人手机号
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param deviceMobileSetDto
     * @return null
     */
    @Async("taskExecutor")
    public void deviceMobileSet(DeviceMobileSetDto deviceMobileSetDto){

        logger.info("请求修改设备手机号接口，para={}",JSONObject.toJSONString(deviceMobileSetDto));

        if(deviceMobileSetDto.getMerId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入运营商id");
        }

        if(deviceMobileSetDto.getDeviceUniqueId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入机器人唯一id");
        }

        if(StringUtils.isBlank(deviceMobileSetDto.getMobile())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入手机号");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(deviceMobileSetDto.getDeviceUniqueId(), deviceMobileSetDto.getMerId());
        if(deviceWechatInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }

        //修改手机号码
        if(StringUtils.isBlank(deviceWechatInfo.getMobile())){
            deviceWechatInfo.setMobile(deviceMobileSetDto.getMobile());
            //查询该手机号对应的归属
            Integer mobiletype = null;
            String mobiletypeResult = Mobiletype.findMobiletype(deviceMobileSetDto.getMobile());
            if(StringUtils.isNotBlank(mobiletypeResult)){
                JSONObject jsonObject = JSONObject.parseObject(mobiletypeResult);
                if(jsonObject != null){
                    JSONObject data = jsonObject.getJSONObject("data");
                    if(data != null){
                        String isp = data.getString("isp");
                        if("电信".equals(isp)){
                            mobiletype = 0;
                        }else if("移动".equals(isp)){
                            mobiletype = 1;
                        }else if("联通".equals(isp)){
                            mobiletype = 2;
                        }
                    }
                }
            }
            //手机号类型不为空
            if(mobiletype != null){
                deviceWechatInfo.setMobiletype(mobiletype);
            }
            deviceWechatInfoMapper.updateById(deviceWechatInfo);
        }
    }

    /**
     * 修改机器人话费余额
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param devicePhonebalUpdateDto
     * @return null
     */
    @Async("taskExecutor")
    @Transactional
    public void devicePhonebalUpdate(DevicePhonebalUpdateDto devicePhonebalUpdateDto){

        logger.info("请求修改话费余额接口，para={}",JSONObject.toJSONString(devicePhonebalUpdateDto));

        if(devicePhonebalUpdateDto.getMerId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入运营商id");
        }

        if(devicePhonebalUpdateDto.getDeviceUniqueId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入机器人唯一id");
        }

        if(devicePhonebalUpdateDto.getPhonebal() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入话费余额");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(devicePhonebalUpdateDto.getDeviceUniqueId(), devicePhonebalUpdateDto.getMerId());
        if(deviceWechatInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }

        //修改话费余额
        int now = DateUtil.getNowTime();
        deviceWechatInfo.setPhonebal(Tools.getDouble(devicePhonebalUpdateDto.getPhonebal()));
        deviceWechatInfo.setUpdateTime(now);
        deviceWechatInfoMapper.updateById(deviceWechatInfo);

        //判断是否触发报警
        if(deviceWechatInfo.getAlarmRuleId() != null){
            AlarmRule alarmRule = alarmRuleMapper.selectById(deviceWechatInfo.getAlarmRuleId(), deviceWechatInfo.getMerId());
            if(alarmRule != null && Tools.getInteger(alarmRule.getStatus()).intValue() == 1) { //报警规则开启才判断
                //判断是否有报警规则-话费余额报警
                if(StringUtils.isNotBlank(alarmRule.getRuleInfo())){
                    List<AlarmRuleContentVo> alarmRuleContentList = JSONObject.parseArray(alarmRule.getRuleInfo(), AlarmRuleContentVo.class);
                    if(alarmRuleContentList != null && alarmRuleContentList.size() > 0){
                        for (AlarmRuleContentVo alarmRuleContentVo : alarmRuleContentList){
                            //设备
                            if("device".equals(alarmRuleContentVo.getSystemType())){
                                //话费余额
                                if("phonebal".equals(alarmRuleContentVo.getAlarmType())){
                                    //报警规则设置的报警值(分)
                                    Integer averageRate = alarmRuleContentVo.getAverageRate();
                                    if(averageRate != null){
                                        //话费余额少于报警值，则报警（元换成分）
                                        if(com.uzai.common.utils.Math.mul(deviceWechatInfo.getPhonebal(), 100) <= averageRate.intValue()){
                                            //话费余额不足，请及时处理！报警设备id：${deviceid},机器人昵称：${name}
                                            AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                                            alarmMsgFeignDto.setMerId(deviceWechatInfo.getMerId());
                                            alarmMsgFeignDto.setType(SysMsgTypeEnum.CPU_MEMORY.getValue()); //CPU/内存/磁盘剩余空间不足/话费充值不足报警
                                            alarmMsgFeignDto.setDeviceUniqueId(deviceWechatInfo.getId());
                                            alarmMsgFeignDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WECHAT.getKey());
                                            //消息
                                            JSONObject ext = new JSONObject();
                                            ext.put("deviceid", deviceWechatInfo.getDeviceId());
                                            String devicename = Tools.getStr(deviceWechatInfo.getDeviceName());
                                            //如果备注不为空，则加上（机器人备注）
                                            if(StringUtils.isNotBlank(deviceWechatInfo.getDeviceRemark())){
                                                devicename = devicename + "("+Tools.getStr(deviceWechatInfo.getDeviceRemark()) +")";
                                            }
                                            ext.put("devicename", devicename);
                                            ext.put("content", "手机号："+Tools.getStr(deviceWechatInfo.getMobile())+"话费余额不足");
                                            alarmMsgFeignDto.setExt(ext.toJSONString());
//                                            UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                                            logger.info("---设备话费余额不足-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

                                            //2024-01-09修改成直接发送MQ
                                            noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

                                            //保持运行日记(GOD平台统计)
                                            logger.info(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_MOBILE_AMOUNT.getValue(),
                                                    deviceWechatInfo.getMerId(), deviceWechatInfo.getRecvmsgType(), deviceWechatInfo.getId(),
                                                    "",0L,
                                                    ext.getString("content"))));

                                            //是否委托手机话费充值（0-不委托;1-委托）
                                            if(Tools.getInteger(alarmRuleContentVo.getMobileRechargeFlag()) == 1){
                                                //充值金额大于0才充值
                                                double mobileRechargeMoney = Tools.getDouble(alarmRuleContentVo.getMobileRechargeMoney());
                                                if(mobileRechargeMoney > 0){
                                                    //查询此时运营商的余额
                                                    Merchant merchant = merchantMapper.selectById(deviceWechatInfo.getMerId());
                                                    if(merchant != null){
                                                        //添加账户明细
                                                        String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
                                                        double balance = Tools.getDouble(merchant.getBalance());
                                                        if(balance >= mobileRechargeMoney + 2){ //大于充值金额+2元手续费，则充值，反之发送报警消息
                                                            //修改账户余额
                                                            merchant.setBalance(balance - mobileRechargeMoney - 2);
                                                            merchant.setUpdateTime(now);
                                                            int j = merchantMapper.updateBalance(merchant);
                                                            if(j <= 0){
                                                                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "网络异常");
                                                            }
                                                            MerAccDetail merAccDetail = new MerAccDetail();
                                                            merAccDetail.setId(IdWorker.getId());
                                                            merAccDetail.setMerId(merchant.getId());
                                                            merAccDetail.setOperateType(2);//支出
                                                            merAccDetail.setMoney(merchant.getBalance());
                                                            merAccDetail.setCgMoney(mobileRechargeMoney + 2); //多扣2元手续费
                                                            merAccDetail.setSourceType(MerAccDetailSourceTypeEnum.MOBILE_RECHARGE.getId());
                                                            merAccDetail.setSubtype("");
                                                            merAccDetail.setTradeno(trandeNo);
                                                            merAccDetail.setCreateTime(now);
                                                            merAccDetail.setUpdateTime(now);
                                                            merAccDetailMapper.insert(merAccDetail);

                                                            //增加手机话费充值记录
                                                            MerMobileRecharge merMobileRecharge = new MerMobileRecharge();
                                                            merMobileRecharge.setId(IdWorker.getId());
                                                            merMobileRecharge.setMerId(merchant.getId());
                                                            merMobileRecharge.setTradeno(trandeNo);
                                                            merMobileRecharge.setMobile(deviceWechatInfo.getMobile());
                                                            merMobileRecharge.setMobiletype(deviceWechatInfo.getMobiletype());
                                                            merMobileRecharge.setMoney(mobileRechargeMoney);
                                                            merMobileRecharge.setStatus(0); //未充值
                                                            merMobileRecharge.setRemark(null);
                                                            merMobileRecharge.setCreateTime(now);
                                                            merMobileRecharge.setUpdateTime(now);
                                                            merMobileRechargeMapper.insertSelective(merMobileRecharge);

                                                            //通知客服钉钉群报警
                                                            DindDingGroupMsgEnum dindDingGroupMsgEnum = DindDingGroupMsgEnum.INVOICE_CHECK;
                                                            if (dindDingGroupMsgEnum != null) {
                                                                SysRunlogWarningDto sysRunlogWarningDto_stopGoods = new SysRunlogWarningDto();
                                                                String text = "有话费需要充值！"
                                                                            + "\n运营商账号：" + merchant.getMobile()
                                                                            + "\n订单编号：" + trandeNo
                                                                            + "\n手机号：" + deviceWechatInfo.getMobile()
                                                                            + "\n金额：" + mobileRechargeMoney;
                                                                sysRunlogWarningDto_stopGoods.setText(text);
                                                                sysRunlogWarningDto_stopGoods.setSecret(dindDingGroupMsgEnum.getSecret());
                                                                sysRunlogWarningDto_stopGoods.setWebhook(dindDingGroupMsgEnum.getWebhook());
                                                                sysRunlogWarningDto_stopGoods.setOpenConversationId(dindDingGroupMsgEnum.getOpenConversationId());
                                                                UzaiRespVo<Object> objectUzaiRespVo_stopGoods = uzaiManageFeignService.sysRunlogWarning(sysRunlogWarningDto_stopGoods);
                                                                logger.info("--通知客服钉钉群报警有话费充值---para={},result={}", JSONObject.toJSONString(sysRunlogWarningDto_stopGoods), JSONObject.toJSONString(objectUzaiRespVo_stopGoods));
                                                            }


                                                        }else{//运营商余额不足，发送报警记录

                                                            //增加手机话费充值失败记录
                                                            MerMobileRecharge merMobileRecharge = new MerMobileRecharge();
                                                            merMobileRecharge.setId(IdWorker.getId());
                                                            merMobileRecharge.setMerId(merchant.getId());
                                                            merMobileRecharge.setTradeno(trandeNo);
                                                            merMobileRecharge.setMobile(deviceWechatInfo.getMobile());
                                                            merMobileRecharge.setMobiletype(deviceWechatInfo.getMobiletype());
                                                            merMobileRecharge.setMoney(mobileRechargeMoney);
                                                            merMobileRecharge.setStatus(2); //充值失败
                                                            merMobileRecharge.setRemark("运营商账号余额少于设置的手机话费充值金额");
                                                            merMobileRecharge.setCreateTime(now);
                                                            merMobileRecharge.setUpdateTime(now);
                                                            merMobileRechargeMapper.insertSelective(merMobileRecharge);

                                                            //运营商账号余额小于设置的手机话费充值金额！报警设备id：${deviceid},机器人昵称：${name}
                                                            AlarmMsgFeignDto alarmMsgFeignDto_recharge = new AlarmMsgFeignDto();
                                                            alarmMsgFeignDto_recharge.setMerId(deviceWechatInfo.getMerId());
                                                            alarmMsgFeignDto_recharge.setType(SysMsgTypeEnum.OTHER_EXCEPTION.getValue()); //其他异常提醒
                                                            alarmMsgFeignDto_recharge.setDeviceUniqueId(deviceWechatInfo.getId());
                                                            alarmMsgFeignDto_recharge.setDeviceType(DeviceTypeEnum.DT_ANDROID_WECHAT.getKey());
                                                            //消息
                                                            JSONObject ext_recharge = new JSONObject();
                                                            StringBuffer content = new StringBuffer();
                                                            content.append("机器人id:").append(deviceWechatInfo.getDeviceId())
                                                                    .append("\n机器人昵称:").append(devicename)
                                                                    .append("\n手机号:").append(deviceWechatInfo.getMobile())
                                                                    .append("\n运营商账号余额小于设置的手机话费充值金额。");

                                                            ext_recharge.put("content", content);
                                                            alarmMsgFeignDto_recharge.setExt(ext_recharge.toJSONString());
//                                                            UzaiRespVo uzaiRespVo_recharge = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto_recharge);
//                                                            logger.info("---运营商账号余额小于设置的手机话费充值金额发送报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto_recharge), JSONObject.toJSONString(uzaiRespVo_recharge));

                                                            //2024-01-09修改成直接发送MQ
                                                            noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto_recharge);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 查询朋友圈跟发商品信息列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqFollowedItemQuery
     * @return null
     */
    public List<PyqFollowedItemVo> pyqFollowedItemFindByList(PyqFollowedItemQuery pyqFollowedItemQuery){

        List<PyqFollowedItemVo> pyqFollowedItemVoList = new ArrayList<>();

        logger.info("-----查询朋友圈跟发商品信息列表-- dto--{}",JSONObject.toJSONString(pyqFollowedItemQuery));

        if(pyqFollowedItemQuery.getSize() == null){
            pyqFollowedItemQuery.setSize(10); //默认一次查询10个
        }

        //查询10分钟之前的商品
        int now = DateUtil.getNowTime();

        PyqFollowedContentQuery pyqFollowedContentQuery = new PyqFollowedContentQuery();
        pyqFollowedContentQuery.setIdStart(pyqFollowedItemQuery.getId());
        pyqFollowedContentQuery.setItemIdNotNull(1); //不能为空
        pyqFollowedContentQuery.setQueryEndTime(pyqFollowedItemQuery.getQueryEndTime());
        pyqFollowedContentQuery.setQueryStartTime(pyqFollowedItemQuery.getQueryStartTime());

        //查询所有的自动发圈配置记录
        Page<PyqFollowedContent> page = new Page<>();
        page.setCurrent(1);//只查第一页
        page.setSize(pyqFollowedItemQuery.getSize()); //每页查询个数
        page.addOrder(OrderItem.asc("id"));//默认id升序
        Long idStart = 0L;
        List<PyqFollowedContent> pyqFollowedContentList = pyqFollowedContentMapper.findByList(page, pyqFollowedContentQuery);
        for (PyqFollowedContent pyqFollowedContent : pyqFollowedContentList){
            try{
                PyqFollowedItemVo pyqFollowedItemVo = new PyqFollowedItemVo();
                BeanUtils.copyProperties(pyqFollowedContent, pyqFollowedItemVo);
                //查询朋友圈评论列表
                List<PyqFollowedComment> pyqFollowedCommentList = pyqFollowedCommentMapper.selectByDeviceUniqueIdAndSnsId(pyqFollowedContent.getDeviceUniqueId(), pyqFollowedContent.getSnsId());
                if(pyqFollowedCommentList != null && pyqFollowedCommentList.size() > 0){
                    List<String> commentList = new ArrayList<>();
                    for (PyqFollowedComment pyqFollowedComment : pyqFollowedCommentList) {
                        commentList.add(pyqFollowedComment.getContent());
                    }
                    pyqFollowedItemVo.setConmentList(commentList);
                }
                pyqFollowedItemVoList.add(pyqFollowedItemVo);
            }catch (Exception e){
                logger.error("--查询朋友圈跟发商品评论失败--error={}",e.getMessage());
            }
        }
        return pyqFollowedItemVoList;
    }

    /**
     * 删除发单历史记录
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param
     * @return null
     */
    public void deleteHistoryFdSendJob(){
        //删除社群群发列表历史记录(一个月之前）
        xxlJobSyncService.deleteFdSendJobHistorySync();
    }

    /**
     * 通过被动僵尸粉添加好友
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param
     * @return null
     */
    public void passZombieFanPassive(PassZombieFanPassiveDto passZombieFanPassiveDto){
        logger.info("通过被动僵尸粉添加好友，passZombieFanPassiveDto={}", JSONObject.toJSONString(passZombieFanPassiveDto));

        if(passZombieFanPassiveDto.getMerId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入运营商id");
        }

        if(StringUtils.isBlank(passZombieFanPassiveDto.getWxid())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入wxid");
        }

        if(passZombieFanPassiveDto.getDeviceUniqueIdPass() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入新添加好友机器人id");
        }

        //状态（0-未请求；1-已请求；2已添加；3-添加失败；4-未满足条件）
        Integer status = passZombieFanPassiveDto.getStatus();
        if(status == null){
            status = 2; //已添加
        }

        //通过微信id查找该被动僵尸粉
        ZombieFanPassive zombieFanPassive = zombieFanPassiveMapper.selectByWxid(passZombieFanPassiveDto.getWxid(), passZombieFanPassiveDto.getMerId());
        if(zombieFanPassive == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该被动僵尸粉不存在");
        }

        //修改状态
        int now = DateUtil.getNowTime();
        zombieFanPassive.setStatus(status);
        zombieFanPassive.setPassTime(now);
        zombieFanPassive.setDeviceUniqueIdPass(passZombieFanPassiveDto.getDeviceUniqueIdPass());
        zombieFanPassive.setUpdateTime(now);
        zombieFanPassiveMapper.updateByIdSelective(zombieFanPassive);

    }

}
